package org.hot100_1;

import org.algorithm.List.ListNode;

public class leetcode31 {
    public ListNode reverseKGroup(ListNode head, int k) {

        if (k==0 || k==1){
            return head;
        }
        ListNode dummy = new ListNode(-1,head);
        ListNode temp = head;
        int length =0;
        while (temp!=null){
            length++;
            temp=temp.next;
        }
        ListNode list = dummy;
        ListNode curr = head;
        ListNode pre = null;
        ListNode next = null;
        for (int i = length; i>=k; i=i-k) {
            for (int j = 0; j < k; j++) {
                next = curr.next;
                curr.next=pre;
                pre=curr;
                curr=next;
            }
            //list为上一次翻转的尾节点，list.next为这次翻转前的头节点，翻转后的尾节点
            ListNode groupEnd = list.next;
//            ListNode groupStart = pre;
            //pre为这次翻转的尾节点
            list.next=pre;
            //curr为下次翻转的头节点
            groupEnd.next=curr;
            list=groupEnd;
        }


        return dummy.next;
    }
}
